const log4js = require('koa-log4');
const session = require('koa-session');
const logger = log4js.getLogger('routes::city');
const nconf = require('nconf');
const router = require('koa-router')();
exports = module.exports = router;
const jwt = require('jsonwebtoken');
const ccap = require('ccap')();

const user_service = require(global.prefixPath + '/services/user');

// 用户注册
router.post('/regiter', async (ctx, next) => {

	var postParams = ctx.request.body;
	console.log(postParams);
	console.log('ctx.session.captcha: ', ctx.session.captcha);

	if (!postParams.code || !ctx.session.captcha || ctx.session.captcha.toLowerCase() != postParams.code.toLowerCase()) {
		return ctx.body = {
			ok: 0,
			msg: '验证码出错'
		};
	}
	try {
		let app = ctx.app;
		delete postParams['code'];
		var user = await user_service.findByName(postParams.username);

		if (user) {
			return ctx.body = {
				ok: 0,
				msg: '用户名已存在'
			};
		}

		var newUser = await user_service.save(postParams);

		console.log(newUser);

		var token = jwt.sign({
			exp: Math.floor(Date.now() / 1000) + parseInt(nconf.get('jwt').expiretime),
			name: newUser.username
		}, app.secret);
		ctx.body = {
			ok: 1,
			token: token
		};
	} catch (err) {
		throw err;
	}
});

// 验证码
router.get('/captcha', async (ctx, next) => {
	return next().then(() => {
		let ary = ccap.get();
		let txt = ary[0];
		let buf = ary[1];
		ctx.body = buf;
		ctx.type = 'image/png';

		console.log('img captcha txt: ', txt);
		console.log(ctx.session);
		ctx.session.captcha = txt;
	});
});

// 更新密码
router.put('/changepwd', async (ctx, next) => {
	var postParams = ctx.request.body;

	var user = await user_service.checkUser({
		username: postParams.username,
		password: postParams.originpwd
	});

	if (!user) {
		ctx.body = {
			ok: 0,
			msg: '原密码错误'
		};
		return;
	}
	else {
		if (postParams.newpwd != postParams.confirmpwd) {
			ctx.body = {
				ok: 0,
				msg: '两次新密码输入的不一致'
			};
			return;
		}

		try {
			var newUser = await user_service.findAndModify({
				username: postParams.username,
				password: postParams.originpwd
			}, {
				password: postParams.newpwd
			});

			console.log('newUser: ', newUser);
			if (newUser) {
				ctx.body = {
					ok: 1
				};
			}
			else {
				ctx.body = {
					ok: 0,
					msg: '更新密码失败'
				};
			}
		}
		catch (e) {
			console.log('modify error: ', e);
			ctx.body = {
				ok: 0,
				msg: '更新密码失败'
			};
			return;
		}
	}
});
